package repository;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.LocalDateTime;

/**
 * @description:
 * @Author Felix Torn
 * @create: 2023-12-20 22:06
 **/
public class ExpenseRecordDAO {
    // SQL语句，用于插入支出记录
    private static final String INSERT_EXPENSE_SQL = "INSERT INTO expenses (amount, datetime, category, note) VALUES (?, ?, ?, ?)";

    public static void main(String[] args) throws SQLException {
        // 示例：记录一笔支出
        recordExpense(50.0, "Groceries", "Bought groceries for the week");
    }

    // 记录支出的方法
    public static void recordExpense(double amount, String category, String note) throws SQLException {
        // 获取数据库连接
        Connection connection = DatabaseConnector.getConnection();
        assert connection != null;
        LocalDateTime currentDateTime = LocalDateTime.now();
        PreparedStatement preparedStatement = connection.prepareStatement(INSERT_EXPENSE_SQL);

        // 将参数设置到SQL语句中
        preparedStatement.setDouble(1, amount);
        preparedStatement.setTimestamp(2, Timestamp.valueOf(currentDateTime));
        preparedStatement.setString(3, category);
        preparedStatement.setString(4, note);

        // 执行SQL语句
        int rowsAffected = preparedStatement.executeUpdate();

        if (rowsAffected > 0) {
            System.out.println("Expense recorded successfully.");
        } else {
            System.out.println("Failed to record expense.");
        }

    }
}
